<?php
declare (strict_types=1);

namespace app\common\middleware;


use app\common\model\Admin;
use app\common\model\AdminLog;
use app\middleware\Response;
use think\facade\Session;

class After
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $response = $next($request);
        self::doLog($request, $response);
        // 添加中间件执行代码
        return $response;
    }

    protected static function doLog($request, $response)
    {
        $agent = $request->header('user-agent');
        $admin_id = Session::pull('admin_id'); //操作人id
        $admin = (new Admin)->findOrEmpty($admin_id);
        $method = $request->method();  //请求方法比如GET POST
        $path = $request->url();   //请求url
        $ip = $request->ip();  //ip
        $param = $request->param();  //请求参数
        $res = $response->getData(); // 返回值
        $title = Session::pull('menu_title'); // 方法名
        $log = [];
        $log['admin_id'] = $admin_id;
        $log['ip'] = $ip;
        $log['path'] = $path;
        $log['title'] = $title;
        $log['user_agent'] = $agent;
        $log['username'] = $admin['username'];
        $log['method'] = $method;
        $log['param'] = json_encode($param, JSON_UNESCAPED_UNICODE);
        $log['response'] = json_encode($res, JSON_UNESCAPED_UNICODE);
        $log['create_time'] = date("Y-m-d H:i:s");
//        var_dump($log);exit();
        (new AdminLog)->save($log);
    }
}
